#!/bin/sh
#
# ltsp-client-setup  Setup/Configure the LTSP client.
#
# chkconfig: 2345 00 65
# description: LTSP client initialization
# config: /usr/share/ltsp/ltsp_config
# pidfile: /var/run/ltsp-client-setip.pid

# Do not load RH compatibility interface.
WITHOUT_RC_COMPAT=1

# Source function library.
. /etc/init.d/functions

# Source configuration.
SourceIfNotEmpty /etc/default/ltsp-client-setup

LOCKFILE=/var/lock/subsys/ltsp-client-setup
RETVAL=0

[ -f /etc/ltsp_chroot ] && SourceIfNotEmpty /usr/share/ltsp/ltsp_config || exit 0

load_modules()
{
    for module in $(env | grep '^MODULE_' | cut -d= -f2); do
	modprobe -q $module
    done
    is_yes "$POWER_BUTTON" && modprobe -q button 2>/dev/null ||:
}

configure_localdev()
{
    if is_yes "$LOCALDEV"; then
	#[ -d /var/run/drives ] || mkdir /var/run/drives
	[ -d /tmp/drives ] || mkdir /tmp/drives
	/usr/sbin/lbuscd || true
	/usr/sbin/ltspfsd -a || true
	# cdrom devices are handled by the cdpingerponger
	#/usr/sbin/cdpinger cdrom # default for usb cdroms
	# and start one for every additional cdrom device
	#if [ -L /dev/cdrom?* ];then
	#    for CDDEV in $(ls /dev/cdrom?*); do
	#	/usr/sbin/cdpinger $(basename ${CDDEV})
	#    done
	#fi
	# handle already plugged devices on login
	#/usr/sbin/delayed_mounter
    fi
}

configure_console()
{
    [ -z "$CONSOLE_KEYMAP" ] || loadkeys "$CONSOLE_KEYMAP"
}

configure_network()
{
    hostname=$(hostname)
    if [ "(none)" = "$hostname" ] ; then
	hostname="$(hostname)"
    else
	echo $hostname > /etc/hostname
    fi
    ipaddr=`ifconfig eth0 | grep inet | awk '{print $2}' | awk -F: '{print $2}'`
    echo "127.0.0.1 localhost $hostname" > /etc/hosts
    echo "$ipaddr $hostname" >> /etc/hosts
    echo "$SERVER server" >> /etc/hosts
    [ -s /etc/hosts.ltsp ] && cat /etc/hosts.ltsp >> /etc/hosts
}

configure_resolver()
{
    if [ -n "$DNS_SERVER" -a -n "$SEARCH_DOMAIN" ]; then
	echo "search $SEARCH_DOMAIN" > /etc/resolv.conf
	echo "nameserver $DNS_SERVER" >> /etc/resolv.conf
    fi
    /sbin/update_chrooted conf
}

configure_syslog()
{
    echo "*.* @${SYSLOG_HOST-$SERVER}" > /etc/syslog.conf
}

configure_fstab()
{
    mount |
	grep -v '^rootfs ' |
	grep ' on / type nfs ' |
	sed -e 's/ (/ /' \
	    -e 's/)$/ 0 0/' \
	    -e 's| on / type | / |' >> /etc/fstab
    echo "tmpfs /tmp tmpfs defaults,nosuid,nodev 0 0" >> /etc/fstab
    mount /tmp
}

configure_x()
{
    # set default configuration file
    xserver_config="/etc/X11/xorg.conf"
    X_CONF="${X_CONF:-$XF86CONFIG_FILE}"
    if [ -n "$X_CONF" ]; then
	cp "$X_CONF" "$xserver_config"
    else
	X_MODE=$(echo "$X_MODE_0,$X_MODE_1,$X_MODE_2" | sed 's/,*$//g')
	# Autoconfigure
	if [ -x /usr/bin/x11_autosetup ]; then
	    XORG_CONF="$xserver_config" /usr/bin/x11_autosetup "${X_MODE:+-x $X_MODE}"
	elif [ -x /usr/bin/x11createconfig ]; then
	    /usr/bin/x11createconfig  > $xserver_config
	    [ -x /usr/bin/x11setupdrv ] && /usr/bin/x11setupdrv
	fi

	# sed not work read-only filesystem	
	cp /etc/X11/xorg.conf /tmp/xorg.conf
	xserver_config="/tmp/xorg.conf"
	
	# Handle overrides of specific parameters
	if [ -n "$XSERVER" ] && [ "$XSERVER" != "auto" ]; then
	    /usr/bin/x11setupdrv --setdrv $XSERVER $xserver_config
	fi
	
	X_DISPLAYSIZE=${X_DISPLAYSIZE:-N}
	if is_yes "$X_DISPLAYSIZE"; then
	    true
	elif is_no "$X_DISPLAYSIZE"; then
	    sed -i -e 's/^\([[:blank:]]*\)\(DisplaySize[[:blank:]]\)/\1#\2/' $xserver_config
	else
	    sed -i -e "s/^\([[:blank:]]*DisplaySize[[:blank:]]*\).*$/\1$X_DISPLAYSIZE/" $xserver_config
	fi
	X_USE_SYNC_RANGES=${X_USE_SYNC_RANGES:-Y}
	if [ -n "$X_HORIZSYNC" -a -n "$X_VERTREFRESH" ]; then
	    sed -i -r -e "s|^([[:blank:]]*HorizSync[[:blank:]]+).*$|\1$X_HORIZSYNC|" $xserver_config
	    sed -i -r -e "s|^([[:blank:]]*VertRefresh[[:blank:]]+).*$|\1$X_VERTREFRESH|" $xserver_config
	fi
	# Color depth preseeding
	[ -n "$X_COLOR_DEPTH" ] && sed -i -r -e "s|^([[:blank:]]*DefaultColorDepth[[:blank:]]+).*$|\1$X_COLOR_DEPTH|" $xserver_config
	# set compatbility for X_VIDEORAM with ltsp 4.x
	X_VIDEO_RAM=${X_VIDEO_RAM:-"$X_VIDEORAM"}
	# set video ram
	[ -n "$X_VIDEO_RAM" ] && sed -i -r -e "s|^([[:blank:]]*VideoRam[[:blank:]]+).*$|\1$X_VIDEO_RAM|" $xserver_config
	# Mouse preseeding options.  Use inputattach if available
	[ -n "$X_MOUSE_DEVICE" ]
	[ -n "$X_MOUSE_PROTOCOL" ]
	[ -n "$X_MOUSE_EMULATE3BTN" ]

	if [ Y = "${USE_XFS}" ]; then
	    [ -z "$XFS_SERVER" ] && XFS_SERVER="$SERVER"
	    [ -z "$XFS_PORT" ] && XFS_PORT=7100
	    sed -i -r -e 's|^([[:blank:]]*FontPath[[:blank:]]+).*$|\1"/usr/share/fonts/bitmap/misc:unscaled\;tcp/'$XFS_SERVER':'$XFS_PORT'"|' $xserver_config
	fi
	
	# DRI
	if [ "${X_DRI}" = N ] ; then
	    sed -i "s/Load  \"dri\"/Disable  \"dri\"/g" $xserver_config
	fi
	if [ "${X_MODULE}" = N ] ; then
	    sed -i "s/Load  \"glx\"/Disable  \"dri\"\n\tDisable  \"dri2\"\n\tDisable  \"glx\"\n\tDisable  \"extmod\"\n\tDisable  \"dbe\"/g" $xserver_config
	    sed -i "s/Load  \"dri\"//g" $xserver_config
	    sed -i "s/Load  \"dbe\"//g" $xserver_config
	fi
	
	# use original
        cp /tmp/xorg.conf /etc/X11/xorg.conf
        rm /tmp/xorg.conf
	xserver_config="/etc/X11/xorg.conf"
		
	# Make sure xkb values only get preseeded if the variables are actually set
	#[ -n "$XKBOPTION" -o -n "$XKBOPTIONS" ] && echo "-option" >> /etc/X11/xinit/Xkbmap
	[ -n "$XKBMODEL" ] && echo "-model $XKBMODEL" >> /etc/X11/xinit/Xkbmap
	[ -n "$XKBLAYOUT" ] && echo "-layout $XKBLAYOUT" >> /etc/X11/xinit/Xkbmap
	[ -n "$XKBRULES" ] && echo "-rules $XKBRULES" >> /etc/X11/xinit/Xkbmap
	[ -n "$XKBVARIANT" ] && echo "-variant $XKBVARIANT" >> /etc/X11/xinit/Xkbmap
	if [ -n "$XKBOPTIONS" ]; then
	    for opt in $XKBOPTIONS; do
		echo "-option $opt" >> /etc/X11/xinit/Xkbmap
	    done
	fi
	[ -n "$XKBOPTION" ] && echo "-option $XKBOPTION" >> /etc/X11/xinit/Xkbmap
	[ -x /usr/bin/x11_autosetup ] || [ -x /usr/bin/x11setupdrv ] && /usr/bin/x11setupdrv
    fi
}

bind_unmounts()
{
    for dir in $temp_copy_dirs; do
	umount $dir
	rm -rf $tmpfs_dir/${dir#/}
    done
}

run_rcfiles()
{
    for rcfile in $(env | sort | awk -F= '$1 ~ /^RCFILE_/ { print $2 }'); do
	[ -x "$rcfile" ] && "$rcfile" $@
    done
}

start()
{
    if [ -f "$LOCKFILE" ]; then
	msg_already_running "ltsp-client-setup"
	RETVAL=1
	return $RETVAL
    fi
    msg_starting $"Setting up LTSP client"
    load_modules || true
    configure_console || true
    configure_network || true
    configure_resolver || true
    configure_fstab || true
    configure_syslog || true
    run_rcfiles || true
    configure_x || true
    configure_localdev || true
    [ "$root_write_method" = "bind_mounts" ] && bind_unmounts
    RETVAL=$?
    touch "$LOCKFILE"
    return $RETVAL
}

stop()
{
    rm -f "$LOCKFILE"
    RETVAL=0
    return $RETVAL
}

status()
{
    if [ -f "$LOCKFILE" ]; then
	echo "This service was last time (re-)started at $(LANG=C LANGUAGE=C /bin/ls -l "$LOCKFILE" --full-time | tr -s ' ' | cut -f 6-10 -d' ')."
	echo "No other status information available for this package."
	echo "All this doesn't mean that there have not been perfomed any other (not init-forced) LTSP client changes since the given time."
    else
	echo "This service hasn't been started since stopped last time."
	echo "This does mean nothing at all (stopping the service doesn't unload the LTSP client)."
    fi
    RETVAL=$?
    return $RETVAL
}

case "$1" in
    start|restart|reload)
	start
	;;
    condrestart|condreload)
	# Nothing to do on condrestart
	RETVAL=0
	;;
    stop|condstop)
	stop
	;;
    status)
	status
	;;
    *)
	msg_usage "${0##*/} {start|stop|restart|reload|status|condrestart|condreload|condstop}"
	RETVAL=1
	;;
esac

exit $RETVAL
